package kr.cadis.clms.dao;

import java.io.Reader;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kr.cadis.clms.model.DailySpend;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class DailySpendDao {

	Reader reader;
	SqlMapClient sqlMap;
	
	public DailySpendDao() {
		try {
			reader = Resources.getResourceAsReader("SqlMapConfig.xml");
			sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
		}
		catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
	}
	
	public boolean insert(DailySpend dailySpend) throws SQLException {
		sqlMap.insert("DailySpend.insert", dailySpend);
		
		//TODO 검토 필요!!
		return true;
	}
	
	public boolean delete(Date spendDate) throws SQLException {
		
		if(sqlMap.delete("DailySpend.delete", spendDate) == 1) { 
			return true;
		} else {
			return false;
		}	
	}
	
	public boolean update(DailySpend dailySpend) throws SQLException {
		if(sqlMap.update("DailySpend.update", dailySpend) == 1) { 
			return true;
		} else {
			return false;
		}	
	}
	
	public DailySpend selectByDate(Date date) throws SQLException {
		DailySpend dailySpend = (DailySpend) sqlMap.queryForObject("DailySpend.selectByDate", date);
		
		return dailySpend;
	}
	
	public List<DailySpend> selectAll() throws SQLException {
		List<DailySpend> dailySpendes = sqlMap.queryForList("DailySpend.selectAll");
		
		return dailySpendes;
	}
	
	public int selectTotalSpendMoneyForThisWeek(String startDateOfThisWeek, String finishDateOfThisWeek) throws SQLException {
		Map<String, String> parameterMap = new HashMap<>();
		
		parameterMap.put("startDateOfThisWeek", startDateOfThisWeek);
		parameterMap.put("finishDateOfThisWeek", finishDateOfThisWeek);
		
		Integer totalSpendMoney = (Integer)sqlMap.queryForObject("DailySpend.selectTotalSpendMoneyForThisWeek", parameterMap);
		
		if(totalSpendMoney == null)
			return 0;
		else
			return totalSpendMoney;
	}
	
	public List<DailySpend> sumTotalSpendMoneyForWeek() throws SQLException {
		List<DailySpend> dailySpends = sqlMap.queryForList("DailySpend.sumTotalSpendMoneyForWeek");
		
		return dailySpends;
	}
	
	public List<DailySpend> sumTotalSpendMoneyForMonth() throws SQLException {
		List<DailySpend> dailySpends = sqlMap.queryForList("DailySpend.sumTotalSpendMoneyForMonth");
		
		return dailySpends;
	}
}
